<?php
/**
 * Created by PhpStorm.
 * User: 64423
 * Date: 2018/10/10
 * Time: 11:27
 */

namespace app\shop\model;


use think\Model;

class GoodsModel extends Model
{
    protected $table = 'dp_goods';
    protected $pk = 'id';
    protected $field = true;

    public function spec()
    {
        return $this->hasMany('GoodsSpecModel','goods_id','id');
    }

    public function category()
    {
        return $this->hasOne('GoodsCategoryModel','id','cate_id');
    }

    public function brand()
    {
        return $this->hasOne('BrandModel','id','brand_id');
    }

    public static function getRes()
    {
        return self::order('id desc')->column('id,name');

    }

    public static function getList()
    {
        $list = self::with('category')->with('brand')->paginate(10);
        foreach ($list as $key => $value){
            $list[$key]['cate_name'] = $value['category']['name'];
            $list[$key]['brand_name'] = $value['brand']['name'];
        }
        return $list;
    }

    public static function getAll()
    {
        $list = self::with('category')->with('brand')->select();
        foreach ($list as $key => $value){
            $list[$key]['cate_name'] = $value['category']['name'];
            $list[$key]['brand_name'] = $value['brand']['name'];
        }
        return $list;
    }

    public static function getListByCondition($where, $p=1, $row=10, $order='')
    {
        $list = self::where($where)
            ->with('category')
            ->with('brand')
            ->field('id,name,cate_id,brand_id,remark,market_price,shop_price,sell_num,use_integral,original_img')
            ->order($order)
            ->order('sort desc')
            ->limit(( ($p-1) * $row ), $p*$row)
            ->select();
        return getImagePath($list, 'original_img');
    }

    public static function getOne($id)
    {
        return self::where('id', $id)->with('spec')->find();
    }

    public static function store($data, $id=0)
    {
        if($id == 0){
            // add
            $goods_id = self::insertGetId($data);
            return $goods_id;
        }else{
            return self::where('id',$id)->update($data);
        }
    }

    public static function del($id)
    {
        return self::where('id',$id)->delete();
    }



}